package controllers

import (
	"commerce/common"
	"commerce/data"
	"commerce/model"
	"commerce/utils"
	"context"
	"fmt"
	"html/template"
	"net/http"
	"path/filepath"
	"strconv"
	"strings"
)

func init() {

	common.Templates["goods"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/goods.html")))
	common.Templates["goods_edit"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/goods_edit.html")))
}

func ListGoods(w http.ResponseWriter, r *http.Request) {

	pageNo, err := strconv.Atoi(r.FormValue("pageNo"))
	if err != nil {
		pageNo = 1
	}
	pageSize, err := strconv.Atoi(r.FormValue("pageSize"))
	if err != nil {
		pageSize = common.PAGE_SIZE
	}

	name := strings.TrimSpace(r.FormValue("name"))

	var page, _ = data.PageGoods(pageNo, pageSize, name)

	if page == nil {
		common.Templates["5xx"].Execute(w, nil)
		return
	}
	// 分页条件查询使用
	var qs = r.URL.RawQuery

	index := strings.Index(r.RequestURI, "&pageNo=")
	var flag bool
	// 这一步操作是点击分页来的
	if index != -1 {
		qs = r.RequestURI[:index]
		flag = true
	} else {
		// 首次点击搜索按钮查询
		flag = false
		qs = "?"
		if len(name) > 0 {
			qs += "name=" + name
		}
	}
	if flag {
		page.Url = qs
	} else {
		page.Url = r.RequestURI + qs
	}

	common.Templates["goods"].Execute(w, page)
}

func AddGoodsUIHandler(w http.ResponseWriter, r *http.Request) {

	// 查所有品牌
	brandList, _ := data.ListAllBrand(1)
	list, _ := data.ListAllCategory()

	g := model.Goods{BrandList: brandList, Categories: list}

	// 查所有属性
	allGoodsAttrValues, err := data.ListAllGoodsAttr()
	if err != nil {
		common.Templates["5xx"].Execute(w, err.Error())
		return
	}
	g.AllGoodsAttrValues = allGoodsAttrValues

	common.Templates["goods_edit"].Execute(w, g)
}

func GetGoodsHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	g, err := data.GetGoodsById(id)

	if err != nil {
		common.Templates["5xx"].Execute(w, err.Error())
		return
	}
	// 查所有品牌
	brandList, _ := data.ListAllBrand(1)
	g.BrandList = brandList

	list, _ := data.ListAllCategory()
	g.Categories = list

	// 查所有属性
	allGoodsAttrValues, err := data.ListAllGoodsAttr()
	if err != nil {
		common.Templates["5xx"].Execute(w, err.Error())
		return
	}
	g.AllGoodsAttrValues = allGoodsAttrValues
	// 回显属性值
	goodsAttrValues, err := data.ListGoodsAttrValueByGoodsId(id)
	if err != nil {
		common.Templates["5xx"].Execute(w, err.Error())
		return
	}
	g.GoodsAttrValues = goodsAttrValues

	// 回显详情图
	imgList, _ := data.ListGoodsImgByGoodsId(id)
	g.GoodsDetailImgList = imgList

	common.Templates["goods_edit"].Execute(w, g)
}

func AddOrEditGoodsHandler(w http.ResponseWriter, r *http.Request) {

	var id = 0
	idVal := r.PostFormValue("id")
	if len(idVal) > 0 {
		id, _ = strconv.Atoi(idVal)
	}
	goodsName := r.PostFormValue("goodsName")
	description := r.PostFormValue("description")
	// 处理商品属性
	goodsAttrValue := r.PostForm["goodsAttrValue"]

	var goodsAttrIds []int
	for _, v := range goodsAttrValue {
		id, _ := strconv.Atoi(strings.Split(v, "_")[0])
		goodsAttrIds = append(goodsAttrIds, id)
	}
	goodsAttrs, err := data.ListGoodsAttrById(goodsAttrIds)

	if len(goodsAttrs) <= 0 {
		common.Templates["5xx"].Execute(w, fmt.Sprintf("%s-%s", "商品属性输入有误！", goodsAttrValue))
		return
	}
	var mainImg = ""
	mf, header, err := r.FormFile("mainImg")
	// 用户上传了主图
	if err == nil && mf != nil {
		uploadedPath, err := utils.Upload(mf, header.Filename)
		if err != nil {
			common.Error.Printf("upload goods main img failed, filename:%s, err:%v", header.Filename, err)
		} else {
			mainImg = uploadedPath
			// 更新操作
			if id > 0 {
				// 删除老的图片(如果有)
				gp, _ := data.GetGoodsById(id)
				if gp != nil && len(gp.MainImg) > 0 {
					fns := strings.LastIndex(gp.MainImg, "/")
					if fns > -1 {
						utils.Delete(gp.MainImg[fns+1:])
					}
				}
			}
		}
	}
	var goodsImgList []model.GoodsImg
	// 处理详情图（由前端网页上传，到这里的是图片地址列表）
	var goodsImgs []model.GoodsImg
	dis := r.PostForm["detailImg"]
	for i, v := range dis {
		goodsImgs = append(goodsImgs, model.GoodsImg{ImgUrl: v, Sort: int8(i)})
	}
	if len(goodsImgs) > 0 {
		goodsImgList, _ = data.ListGoodsImgByGoodsId(id)
	}

	// 商品详情图列表
	//var goodsImgReqList []req.GoodsImgReq
	//var f multipart.File
	//fhs := r.MultipartForm.File["detailImg"]
	//for _, fh := range fhs {
	//	f, err = fh.Open()
	//	if err != nil {
	//		continue
	//	}
	//	goodsImgReqList = append(goodsImgReqList, req.GoodsImgReq{f, fh})
	//}
	//length := len(goodsImgReqList)

	priority, _ := strconv.Atoi(r.PostFormValue("priority"))
	brandId, _ := strconv.Atoi(r.PostFormValue("brandId"))
	categoryId, _ := strconv.Atoi(r.PostFormValue("categoryId"))
	//var gp *model.Goods
	//var goodsImgs []model.GoodsImg
	//if id > 0 {
	//gp, _ = data.GetGoodsById(id)
	//if gp != nil && len(gp.MainImg) > 0 {
	//	// 首字符是/,要去掉
	//	gp.MainImg = gp.MainImg[1:]
	//	mainImg = gp.MainImg
	//}
	//goodsImgList, _ := data.ListGoodsImgByGoodsId(id)

	//	// 用户上传了详情图（修改）
	//	if length > 0 {
	//
	//		for i, _ := range goodsImgList {
	//			if len(goodsImgList[i].ImgUrl) > 0 {
	//				// 去掉首字符 /
	//				goodsImgList[i].ImgUrl = goodsImgList[i].ImgUrl[1:]
	//			}
	//		}
	//
	//		if length != len(goodsImgList) {
	//			// 删除已有的
	//			deleteOldGoodsDetailImgList(goodsImgList)
	//			// 保存更新的到本地
	//			goodsImgs = saveGoodsDetailImgList(goodsImgReqList)
	//		} else {
	//			flag := false
	//			for i, v := range goodsImgReqList {
	//				// 有修改
	//				if !strings.HasSuffix(goodsImgList[i].ImgUrl, v.Fh.Filename) {
	//					flag = true
	//					break
	//				}
	//			}
	//			if flag {
	//				// 删除已有的
	//				deleteOldGoodsDetailImgList(goodsImgList)
	//				// 保存更新的到本地
	//				goodsImgs = saveGoodsDetailImgList(goodsImgReqList)
	//			}
	//		}
	//	}
	//} else if length > 0 {
	//	// 保存图片到本地
	//	goodsImgs = saveGoodsDetailImgList(goodsImgReqList)
	//}
	g := model.Goods{Id: id, Name: goodsName, Description: description,
		Priority: priority, MainImg: mainImg, BrandId: brandId, CategoryId: categoryId}
	if id <= 0 {
		id, err = data.AddGoods(context.Background(), g, goodsAttrValue, goodsAttrs, goodsImgs)
	} else {
		id, err = data.UpdateGoods(context.Background(), g, goodsAttrValue, goodsAttrs, goodsImgs)
	}
	// db 更新成功后
	if err == nil {
		// 删除老的图片
		if len(goodsImgList) > 0 {
			var is []string
			for _, v := range goodsImgList {
				is = append(is, v.ImgUrl)
			}
			go utils.BatchDelete(is)
		}
	}
	//重定向到列表
	http.Redirect(w, r, "/commerce/api/v2/goods/list", http.StatusFound)
}

//func saveGoodsDetailImgList(list []req.GoodsImgReq) []model.GoodsImg {
//
//	prefix := common.AppConfig.ImgUploadPath + "goodsDetail/" + utils.FilenamePrefix() + "_"
//
//	var goodsImgList []model.GoodsImg
//	var path string
//	for i, v := range list {
//		path = prefix + v.Fh.Filename
//		dst, _ := os.Create(path)
//		io.Copy(bufio.NewWriter(dst), bufio.NewReader(v.F))
//
//		goodsImgList = append(goodsImgList, model.GoodsImg{ImgUrl: "/" + path, Sort: int8(i)})
//	}
//	return goodsImgList
//}

//func deleteOldGoodsDetailImgList(list []model.GoodsImg) {
//	// 删除之前的
//	var exist = true
//	for _, v := range list {
//		if _, err := os.Stat(v.ImgUrl); os.IsNotExist(err) {
//			exist = false
//		}
//		if exist {
//			os.Remove(v.ImgUrl)
//		}
//	}
//}

func OnSaleGoodsHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	skuIds, _ := data.ListSkuByGoodsId(id, 1)
	// 上架商品需要确保至少有一个它名下的sku 是上架状态
	if len(skuIds) == 0 {
		common.DisplayAppErr(w, fmt.Errorf("需要此商品下至少一个sku上架"), "需要此商品下至少一个sku上架", http.StatusOK)
		return
	}
	data.UpdateGoodsStatus(id, 1)

	common.DisplayOk(w, "上架成功!", http.StatusOK)

}

func OffSaleGoodsHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	// 更新此商品及它名下的所有（上架状态的）sku状态为下架
	data.UpdateGoodsAndSkuStatus(context.Background(), id, 0)

	common.DisplayOk(w, "下架成功!", http.StatusOK)
}
